<template>
  <div>
    <myDivider name="楼宇管理"></myDivider>
    <!-- <el-alert :closable="false" title="三级菜单1" type="success" /> -->
    <el-page-header @back="goBack" :content="operateType == 'update' ? '修改楼宇信息' : '新增楼宇信息'">
    </el-page-header>
    <div class="insertPopulation">
      <el-form ref="reinsertForm" :model="reinsertForm" label-width="80px" :inline="true" :rules="insertRules">
        <el-form-item label="楼宇名称:" :label-width="formLabelWidth" class="formItemStyle" prop="name">
          <el-input v-model="reinsertForm.name" placeholder="请输入名称" maxlength="50" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="归属小区:" prop="residentialQuartersId" :label-width="formLabelWidth" class="formItemStyle">
          <el-select disabled v-model="reinsertForm.residentialQuartersId" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in residentialQuartersIdData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="楼层数:"  prop="countOfFloors" :label-width="formLabelWidth" class="formItemStyle">
          <el-input placeholder="请输入楼层数" type="number"
            @input="reinsertForm.countOfFloors = reinsertForm.countOfFloors.replace(/[^\d]/g, '')"
            v-model="reinsertForm.countOfFloors" autocomplete="off" style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="楼宇高度:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input oninput="if(value.length > 4) value=value.slice(0, 4)"
            @input="reinsertForm.height = reinsertForm.height.replace(/[^\d]/g, '')" placeholder="请输入楼层高度" type="number"
            v-model="reinsertForm.height" autocomplete="off" style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="朝向:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.toward" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in towardData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="类型:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.type" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in typeData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="结构:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.structure" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in structureData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="用途:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.purpose" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in purposeData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 添加取消 -->
      <el-form ref="form" :model="reinsertForm" label-width="80px" style="height: 41px;">
        <el-form-item style="float: right; margin-bottom: 80px;">
          <el-button type="primary" @click="onSubmitUpdate" v-if="operateType == 'update'">修改</el-button>
          <el-button type="primary" @click="onSubmit" v-if="operateType == 'insert'">添加</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>

      <el-divider></el-divider>
    </div>
  </div>
</template>



<script>
import VDistpicker from "v-distpicker";
import { getUserList } from "../../user/user";
import {
  getFatherAgencies,
  addXiaoQu,
  getDictionaryList,
  getInDetail,
  updateinstInfo,
  getcityList,
  getShangJiJiGouList,
  getXiaoQulist,
  addbuilding,
  getChaoXianglist,
  getJieGoulist,
  getYongTUlist,
  getTypelist
} from "./building";
export default {
  components: { VDistpicker },
  data() {

    return {
      //下拉类型列表
      typeData: [
        { name: '自建房', type: '1' },
        { name: '非自建房', type: '2' },
      ],
      // 下拉用途列表
      purposeData: [],
      // 结构下拉列表
      structureData: [],
      //朝向下拉列表
      towardData: [
      ],
      //小区下拉列表
      residentialQuartersIdData: [
      ],

      affiliatedManagementDepartmentIdData: [],
      affiliatedAgencyIdData: [],
      developerCompanyIdData: [{ name: "1号", type: 1 }],
      contractorCompanyIdData: [{ name: "1号", type: 1 }],
      criCodeDefaultShow: true,
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          let { level } = node;
          getcityList(node.value).then(res => {
            res.forEach(el => {
              el.value = el.criCode;
              el.label = el.criName;
              el.leaf = level >= 3;
            });
            resolve(res);
          });
        }
      },
      options: [],

      // 是否认证
      authenticationStatusData: [
        { name: "未认证", id: "0" },
        { name: "已认证", id: "1" }
      ],
      formLabelWidth: "120px", //控制前面label的宽度

      reinsertForm: {
        name: "",
        residentialQuartersId: "",
        countOfFloors: "",
        height: "",
        toward: "",
        type: "",
        structure: "",
        purpose: ""
      },
      insertRules: {
        name: [
          {
            required: true,
            message: "楼宇名称不能为空",
            trigger: "blur"
          }
        ],
        countOfFloors: [
          {
            required: true,
            message: "楼层数不能为空",
            trigger: "blur"
          }
        ],
        residentialQuartersId: [
          {
            required: true,
            message: "请选择归属小区",
            trigger: "change"
          }
        ],
      },
      operateType: "insert",
      genderListData: [
        { id: "0", name: "女" },
        { id: "1", name: "男" }
      ],
      fatherAgenciesOptionData: [],
      typeOptionData: [],
      query: {
        name: "",
        account: ""
      },
      userData: [], //用户数据
      pageNum: 0,
      pageSize: 10,
      totalSize: 0
    };
  },

  activated() {

    if (this.$route.query.operateType == "update") {
      this.operateType = "update";
      // 获取楼宇信息详情
      this.getbuildingXiangQing()
    } else {
      // 数据清空
      for (let i in this.reinsertForm) {
        this.reinsertForm[i] = "";
      }
      this.operateType = "insert";
    }

    //刚进入页面加载
    // this.queryUserList();
    this.getFatherAgenciesOptionData("");
    this.$nextTick(() => {
      this.$refs.reinsertForm.clearValidate()
    })
  },
  deactivated() {
    this.$set(this.reinsertForm, 'name', '')
    this.$set(this.reinsertForm, 'residentialQuartersId', '')
    this.$set(this.reinsertForm, 'countOfFloors', '')
    this.$set(this.reinsertForm, 'height', '')
    this.$set(this.reinsertForm, 'toward', '')
    this.$set(this.reinsertForm, 'type', '')
    this.$set(this.reinsertForm, 'structure', '')
    this.$set(this.reinsertForm, 'purpose', '')
  },
  mounted: function () {
    //初始化选项数据
    this.getAgencyTypeOptionData();
  },

  methods: {
    // 楼宇信息详情
    async getbuildingXiangQing() {
      let res = await getInDetail(this.$route.query.id)
      console.log(res, '楼宇信息详情');
      this.reinsertForm = res
    },
    //级联选择器获取焦点
    cascaderClick() {
      this.getAgencyTypeOptionData();
      this.props.lazy = true;
    },
    handleChange(val) {
      console.log(val);
      this.reinsertForm.criCode = val[val.length - 1];
    },
    /**
     *  新增
     */
    onSubmit() {
      console.log(this.reinsertForm, "新增信息");
      let {
        name, residentialQuartersId, countOfFloors, height, toward, type, structure, purpose
      } = this.reinsertForm
      let params = {
        name, residentialQuartersId, countOfFloors, height, toward, type, structure, purpose
      }
      let that = this;
      this.$refs["reinsertForm"].validate(valid => {
        if (valid) {
          addbuilding(params).then(res => {
            console.log(res, "新增接口返回信息");
            if (res.data.code == 200) {
              this.$message({
                message: "新增成功",
                type: "success"
              });
              this.goBack();
            } else {
              if (res.data.message == "值重复") res.data.message = "机构名称不能重复";
              this.$message({
                message: res.data.message,
                type: "warning"
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    /**
     *  修改
     */
    onSubmitUpdate() {
      console.log(this.reinsertForm, "修改信息");
      this.reinsertForm.id = this.$route.query.id;
      updateinstInfo(this.reinsertForm).then(res => {
        if (res.code == 200) {
          this.$message({
            message: "修改成功",
            type: "success"
          });
          this.goBack();
        } else {
          this.$message({
            message: res.message,
            type: "warning"
          });
        }
      });
    },

    /**
     *  上一页
     */
    goBack() {
      this.$router.back(-1);
      // this.$router.push({
      //   path: "/residential/reDetail",
      //   query: {
      //     id: this.$route.query.id,
      //     operateType: 'binding'
      //   }
      // });
    },



    /**
     * 获取下拉菜单数据
     */
    async getFatherAgenciesOptionData(name) {
      // 获取小区列表 START
      let logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
      let XIaoquData = await getXiaoQulist({
        "pageNum": 1,
        "pageSize": 1000000,
        "name": '', //小区名称（传不传都行）
        "code": '', //街道code
        "deptName": '', //所属管理部门名称
        "type": '', //条件分类:  小区名name  居委会agencyName 机构companyName 开发商developerName 承建商contractorName
        "keywords": '', //条件内容
        unitType: logOnUser.unitType,
        unitId: logOnUser.unitId,
      });
      console.log(XIaoquData, "XIaoquData");
      this.residentialQuartersIdData = [];
      XIaoquData.list.forEach(el => {
        this.residentialQuartersIdData.push({
          name: el.name,
          type: el.id
        });
      });
      this.reinsertForm.residentialQuartersId = this.$route.query.residentialId * 1
      // 获取小区列表 END

      // 获取朝向列表 start
      this.towardData = []
      let ChaoXiangData = await getChaoXianglist();
      console.log(ChaoXiangData, "ChaoXiangData");
      ChaoXiangData.forEach(el => {
        this.towardData.push({
          name: el.name,
          type: el.value
        })
      })
      // 获取朝向列表 end
      // 结构列表 start
      this.structureData = []
      let JieGouData = await getJieGoulist();
      console.log(JieGouData, "JieGouData");
      JieGouData.forEach(el => {
        this.structureData.push({
          name: el.name,
          type: el.value
        })
      })
      // 结构列表 end
      // 下拉用途列表 start
      this.purposeData = []
      let YongTUData = await getYongTUlist();
      console.log(YongTUData, "YongTUData");
      YongTUData.forEach(el => {
        this.purposeData.push({
          name: el.name,
          type: el.value
        })
      })
    },
    dgfun(res) {
      let arr = [];
      res.forEach(el => {
        // 如果有孩子们，继续遍历
        if (el.childrenList != null) {
          el.childrenList = this.dgfun(el.childrenList);
        }
        arr.push({
          value: el.criCode,
          label: el.criName,
          children: el.childrenList
        });
      });
      return arr;
    },
    /**
     * 获取类型字典数据
     */
    getAgencyTypeOptionData() {
      // 获取省份信息
      getcityList("000000").then(res => {
        this.options = [];
        res.forEach(el => {
          this.options.push({
            value: el.criCode,
            label: el.criName
          });
        });
      });
      getDictionaryList("agency_type").then(res => {
        this.typeOptionData = res.data;
      });
    },



    //按条件查询菜单列表
    // queryUserList() {
    //   getUserList(
    //     this.query.userCode,
    //     this.query.userName,
    //     "1",
    //     this.pageNum,
    //     this.pageSize
    //   ).then(res => {
    //     this.userData = res.list;
    //     this.pageNum = res.pageNum;
    //     this.pageSize = res.pageSize;
    //     this.totalSize = res.total;
    //   });
    // }
  }
};
</script>
<style lang="less" scoped>
.szdqBox {
  display: flex;

  .addressStyle {
    width: 350px;
    display: flex;
    justify-content: space-between;
    flex-wrap: nowrap;

    /deep/ label {
      width: 33%;

      select {
        width: 100%;
      }
    }
  }
}

.insertPopulation {
  margin-top: 90px;
  margin-left: 130px;
  height: 50%;
}

.menuTable {
  margin-top: 100px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.menuTable .cell {
  text-align: center;
}

.findValue {
  width: 13%;
  margin-top: 20px;
  margin-left: 15px;
}

.operation {
  margin-right: 50px;
  float: right;
  margin-top: 20px;
}

.formStyle {
  width: 1300px;
  margin: 20px auto;
}

.formItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}

.pageFooter {
  margin-top: 3%;
  margin-left: 40%;
}

.pageFooterFather {
  top: 84%;
  position: relative;
  width: 100%;
}

.el-cascader-menu {
  height: fit-content;
  width: fit-content;
}

.birthdayDateItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}
</style>
